package lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class SpintLockDemo {

    //原子引用线程
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "\t come in ");

        while (!atomicReference.compareAndSet(null, thread)) {


        }
    }

    public void myUnLock() {
        Thread thread = Thread.currentThread();

        atomicReference.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t myUnLock()");
    }
    public static void main(String[] args) {

        SpintLockDemo spintLockDemo = new SpintLockDemo();

            new Thread(() -> {
                    //线程要执行的代码
                spintLockDemo.myLock();
                try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }

                spintLockDemo.myUnLock();
                 },"AAAA").start();

                try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

            new Thread(() -> {
                //线程要执行的代码
                spintLockDemo.myLock();
                try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
                spintLockDemo.myUnLock();

            },"BBB").start();

    }
}
